<?php
/**
 * 微信公众平台接口
 * 
 * [WeEngine System] Copyright (c) 2013 WE7.CC
 */
// debug
// debug
if(!empty($_GET['mode']) && $_GET['mode'] == 'debug') {
	$_SERVER['REQUEST_METHOD'] = 'POST';
	$_GET['hash'] = $_GET['hash'];
	$_GET['timestamp'] = time();
	$_GET['nonce'] = 'd3f5bae6';
	$_GET['signature'] = '799e4d6f3fe68043b636a36be11e214246f68a89';
	$GLOBALS['HTTP_RAW_POST_DATA'] = '<xml><ToUserName><![CDATA[gh_cc1cc1bc092c]]></ToUserName>
    <FromUserName><![CDATA[otM6Jjlerqt12mYSzUHDFkx_lmI]]></FromUserName>
    <CreateTime>'.time().'</CreateTime>
    <MsgType><![CDATA[text]]></MsgType>
    <Content><![CDATA[' . $_GET['content'] . ']]></Content>
    </xml>';
	//     $GLOBALS['HTTP_RAW_POST_DATA'] = '<xml><ToUserName><![CDATA[gh_9d5fb3127c88]]></ToUserName>
	//     <FromUserName><![CDATA[oOGSJjq0sjtgLxiToYPXX2i6stJw]]></FromUserName>
	//     <CreateTime>1366125554</CreateTime>
	//     <MsgType><![CDATA[event]]></MsgType>
	//     <Event><![CDATA[subscribe]]></Event>
	//     <EventKey><![CDATA[]]></EventKey>
	//     </xml>';
}
// end debug
require './source/bootstrap.inc.php';
require model('rule');

$sql = "SELECT `weid`,`hash`,`token`,`default_period` FROM " . tablename('wechats') . " WHERE `hash`=:hash LIMIT 1";
$wechat = pdo_fetch($sql, array(':hash' => $_GPC['hash']));
if(empty($wechat)) {
    exit('Access Denied');
}
$_W['wechat'] = $wechat;
$_W['weid'] = $wechat['weid'];
$cfg = array();
$cfg['token'] = $_W['wechat']['token'];
$cfg['matcher'] = 'matcher';
$cfg['after'] = 'after';
$cfg['before'] = 'before';
//todo 获取特定微信账号启用的模块
member_modules();
$cfg['modules'] = array_keys($GLOBALS['_W']['setting']['modules']);
$engine = new WeEngine($cfg);
$engine->start();

/**
 * 匹配关键字
 * 匹配优先级:完全匹配，模糊匹配，正则匹配
 * 多条关键字时,默认使用最新的
 *
 * @param string $input 要进行测试的内容
 * @return array 元组数据
 *      modules : 
 *          模块名称集合. 键名为 模块名, 键值为 匹配次数, 按照匹配次数倒序排列
 *      rules :
 *          所有匹配的关键字规则集合, 格式:
 *          关键字对象集合元素的成员包括 id weid name module
 */
function matcher($input) {
	$result = array();
	if (!isset($input)) {
		return $result;
	}
	
    global $_W;
	//优先获取全匹配的一条
    $condition = "`rid` IN (SELECT `id` FROM " . tablename('rule') . " WHERE `weid`={$_W['wechat']['weid']})";
	$keywords = rule_keywords_search($condition . " AND `content` = '" . addslashes($input) . "'");
	if (empty($keywords)) {
		$needles = rule_keywords_search($condition);
		foreach($needles as $needle) {
			$matched = false;
			switch($needle['type']) {
				case '1':
					$matched = $needle['content'] == $input;
					break;
				case '2':
					$matched = stripos($input, $needle['content']) !== false;
					break;
				case '3':
					$matched = preg_match($needle['content'], $input) !== 0;
					break;
			}
			if($matched) {
				$keywords[] = array(
					'rid' => $needle['rid'],
					'content' => $needle['content'],
					'type' => $needle['type'],			
				);
			}
		}
	}
	if (empty($keywords)) {
		return $result;
	}
	$rids = array();
	foreach($keywords as $k) {
		$rids[] = $k['rid'];
	}
	$counts = array_count_values($rids);
	$condition = ' `id` IN (' . implode(array_unique($rids), ',') . ')';
	$rules = rule_search($condition);
	if (empty($rules)) {
		return $result;
	}
	foreach($rules as &$rule) {
		$modules[$rule['module']] = $counts[$rule['id']];
	}
	arsort($modules);
	$result = array(
		'modules' => $modules,
		'rules' => $rules,		
	);
    return $result;
}

function after($message, $module) {
    global $_W, $wechat;
    if (!empty($module['default'])) {
    	//计算模块优先级
    	$level = array();
    	foreach ($_W['setting']['modules'][$wechat['weid']] as $row) {
    		if (!empty($row['displayorder'])) {
    			$level[$row['displayorder']] = $row;
    		}
    	}
    	$response = '';
    	for ($i = 1; $i <= 5; $i++) {
    		if (!empty($response)) {
    			break;
    		}
    		if (empty($level[$i])) {
    			continue;
    		}
    		$_W['module'] = $level[$i]['name'];
    		$processor = WeUtility::createModuleProcessor($_W['module']);
    		$processor->message = $message;
    		$processor->inContext = false;
    		$processor->rules[] = array();
    		$response = $processor->respond();
    	}
    	if (empty($response)) {
    		if (!empty($wechat['default_period']) && empty($_W['cache']['default_period'])) {
    			exit;
    		}	
    	} else {
    		exit(WeUtility::response($response));
    	}
    }
    return TRUE;
}

function before($message) {
	global $_W, $wechat;
	if (!empty($wechat['default_period'])) {
		$_W['cache']['default_period'] = TRUE;
		$row = pdo_fetch("SELECT id, lastupdate FROM ".tablename('log_message')." WHERE from_user = '{$message['from']}' AND weid = '{$_W['weid']}'");
		if (!empty($row)) {
			if (TIMESTAMP - intval($row['lastupdate']) > intval($wechat['default_period'])) {
				$_W['cache']['default_period'] = TRUE;
			} else {
				$_W['cache']['default_period'] = FALSE;
			}
		}
		
		if (!empty($row)) {
			pdo_update('log_message', array('lastupdate' => TIMESTAMP), array('id' => $row['id']));
		} else {
			pdo_insert('log_message', array('from_user' => $message['from'], 'lastupdate' => TIMESTAMP, 'weid' => $_W['weid']));
		}
	}
}